﻿@inherits BaseEditFormWithOption<OA_UserFormDTO, object>

@if (Data?.Steps?.Count > 0)
{
    <Steps ProgressDot=@customDot>
        @foreach (var item in Data.Steps)
        {
            <Step Status="@StatusToStep(@item.Status)" Title="@item.Label" Description="@item.ActRules?.ToString()" />
        }
        </Steps>
}

<Form @ref="_form" Model="@Data" Class="ant-advanced-search-form">
    <Row Gutter="24">
        <GridCol Span="6">
            <FormItem Label="开始时间">
                <DatePicker @bind-Value="@context.StartTime" TValue="DateTime?" ShowTime="true" Format="yyyy-MM-dd HH:mm:ss" AllowClear />
            </FormItem>
        </GridCol>
        <GridCol Span="6">
            <FormItem Label="结束时间">
                <DatePicker @bind-Value="@context.EndTime" TValue="DateTime?" ShowTime="true" Format="yyyy-MM-dd HH:mm:ss" AllowClear />
            </FormItem>
        </GridCol>
        <GridCol Span="12">
            <FormItem Label="摘要">
                <Input @bind-Value="@context.Text" AutoComplete=false />
            </FormItem>
        </GridCol>
    </Row>
    <Row Gutter="24">
        <GridCol Span="6">
            <FormItem Label="申请人">
                <Select TItem="SelectOption"
                        TItemValue="string"
                        @bind-Value="@context.ApplicantUserId"
                        AllowClear
                        DataSource="Users"
                        LabelName="@nameof(SelectOption.Text)"
                        ValueName="@nameof(SelectOption.Value)"
                        Placeholder="请选择申请人" />
            </FormItem>
        </GridCol>
        <GridCol Span="6">
            <FormItem Label="紧急程度">
                <Select TItem="SelectOption"
                        TItemValue="string"
                        @bind-Value="@context.GradeString"
                        AllowClear
                        DataSource="Grades"
                        LabelName="@nameof(SelectOption.Text)"
                        ValueName="@nameof(SelectOption.Value)"
                        Placeholder="请选择紧急程度" />
            </FormItem>
        </GridCol>
        <GridCol Span="12">
            <FormItem Label="备注">
                <Input @bind-Value="@context.Remarks" AutoComplete=false />
            </FormItem>
        </GridCol>
    </Row>
    <Row Gutter="24">
        <GridCol Span="6">
            <FormItem>
                <LabelTemplate>
                    <Select TItem="SelectOption"
                            TItemValue="string"
                            @bind-Value="@context.SubType"
                            AllowClear
                            DataSource="Types"
                            LabelName="@nameof(SelectOption.Text)"
                            ValueName="@nameof(SelectOption.Value)"
                            style="min-width:100px" />
                </LabelTemplate>
                <ChildContent>
                    <Input @bind-Value="@context.Flag" AutoComplete=false />
                </ChildContent>
            </FormItem>
        </GridCol>
        <GridCol Span="12">
            <FormItem Label="附件">
                <UploadFile File="@context.Appendix" MaxCount="1" />
            </FormItem>
        </GridCol>
    </Row>

</Form>

@if (Data?.Comments?.Count > 0)
{
    <AntList DataSource="@Data.Comments" TItem="OA_UserFormStepDTO">
        <ListItem>
            <ListItemMeta Description="@context.Remarks">
                <TitleTemplate>
                    @context.CreatorName @context.RoleNames @context.CreateTime.ToString("yyyy-MM-dd HH:mm:ss") @StatusToText(@context.Status)
                </TitleTemplate>
            </ListItemMeta>
        </ListItem>
    </AntList>
}
@if (Data?.Status == 1)
{
    <Row>
        <GridCol Span="24">
            <RadioGroup @bind-Value="@Status">
                <Radio Value="100">通过</Radio>
                <Radio Value="2">驳回上一级</Radio>
                <Radio Value="3">驳回重提</Radio>
                <Radio Value="4">否决</Radio>
            </RadioGroup>
            <Input @bind-Value="@Remark" Placeholder="意见" AutoComplete=false />
        </GridCol>
    </Row>
}

<div>
    <Space Size="@("small")" style="margin-top:10px">
        <SpaceItem>
            <Button Type="@ButtonType.Primary" OnClick="()=>OpenEditor()">查看流程图</Button>
        </SpaceItem>
    </Space>
    <Space Size="@("small")" style="float:right;margin-top:10px">
        @if (Data?.Status == 1)
        {
            if (Data?.CreatorId == Operator.UserId)
            {
                <SpaceItem>
                    <Button Type="@ButtonType.Primary" Danger OnClick="()=>DisCard()">废弃</Button>
                </SpaceItem>
            }
            <SpaceItem>
                <Button Type="@ButtonType.Primary" OnClick="()=>EventData()">审批</Button>
            </SpaceItem>
        }
        @if (Data?.Status == 0)
        {
            <SpaceItem>
                <Button Type="@ButtonType.Primary" OnClick="()=>PreStep()">预览流程</Button>
            </SpaceItem>
            <SpaceItem>
                <Button Type="@ButtonType.Primary" OnClick="()=>SaveData()">提交</Button>
            </SpaceItem>
        }
        <SpaceItem>
            <Button Type="@ButtonType.Primary" OnClick="()=>Close()">关闭</Button>
        </SpaceItem>
    </Space>
</div>

<style>
    [data-theme='compact'] .ant-advanced-search-form,
    .ant-advanced-search-form {
        padding: 24px;
        background: #fbfbfb;
        border: 1px solid #d9d9d9;
        border-radius: 2px;
    }

        [data-theme='compact'] .ant-advanced-search-form .ant-form-item,
        .ant-advanced-search-form .ant-form-item {
            display: flex;
        }

        [data-theme='compact'] .ant-advanced-search-form .ant-form-item-control-wrapper,
        .ant-advanced-search-form .ant-form-item-control-wrapper {
            flex: 1;
        }
</style>

@code
{
    [Inject]
    protected ModalService ModalService { get; set; }
    [Inject]
    protected IOperator Operator { get; set; }

    public EditForm()
    {
        Area = "OA_Manage";
    }
    RenderFragment customDot = @<span>
        step {index} status: {status}
    </span>
    ;
    private List<SelectOption> Users { get; set; }
    private List<SelectOption> Types { get; set; }
    private List<SelectOption> Grades { get; set; }
    private List<OA_UserFormStepDTO>? Comments { get; set; }
    private int Status { get; set; } = 100;
    private string Remark;

    public string StatusToStep(int status)
    {
        switch (status)
        {
            case 100:
                return "finish";
            case 1:
            case 7:
            case 6:
            case 10:
            case 99:
                return "process";
            case 2:
            case 3:
            case 4:
            case 5:
            case 8:
                return "error";
            default:
                return "wait";
        }
    }

    public string StatusToText(int status)
    {
        switch (status)
        {
            case 100:
                return "通过";
            case 1:
                return "审批中";
            case 6:
                return "挂起";
            case 7:
                return "恢复";
            case 10:
                return "审批中";
            case 99:
                return "部分审批";
            case 2:
                return "驳回上一级";
            case 3:
                return "驳回重提";
            case 4:
                return "否决";
            case 5:
                return "废弃";
            case 8:
                return "错误";
            default:
                return "等待";
        }
    }

    protected override async Task OnInitializedAsync()
    {
        using (var waitfor = WaitFor.GetWaitFor(this))
        {
            await GetUsers();
            await base.OnInitializedAsync();
            GetTypes();
            GetGrades();
        }
    }

    private void GetTypes()
    {
        UserData.ItemSource.TryGetValue(Data?.Type, out var types);
        Types = new List<SelectOption>(types ?? new List<SelectOption>());
    }
    private void GetGrades()
    {
        UserData.ItemSource.TryGetValue("Grade", out var grades);
        Grades = new List<SelectOption>(grades ?? new List<SelectOption>());
    }

    private async Task GetUsers()
    {
        try
        {
            Users = await UserData.GetBase_User();
        }
        catch (Exception ex)
        {
            await MessageService.Error(ex.Message);
        }
    }

    private async void OpenEditor()
    {
        var modalConfig = new ModalOptions();
        modalConfig.Title = "查看流程";
        //modalConfig.Style = "top:20px;";
        // In order for Dispose in ConfirmTemplateDemo to take effect every time it is closed
        //modalConfig.BodyStyle += "overflow-y: auto;";
        modalConfig.DestroyOnClose = true;
        modalConfig.Centered = true;
        modalConfig.Width = 1000d;
        modalConfig.Footer = null;

        var modalRef = await ModalService.CreateModalAsync<OA_DefForm.TreeEditForm, object>(modalConfig, Data?.WorkflowJSON);

        modalRef.OnOk = () =>
        {
            return Task.CompletedTask;
        };
    }

    private async void PreStep()
    {
        using (var waitfor = WaitFor.GetWaitFor(this))
        {
            try
            {
                var result = await DataProvider.PostData<List<OA_Step>>($"/OA_Manage/OA_UserForm/PreStep", Data.ToJson());
                if (!result.Success)
                {
                    throw new Exception(result.Msg);
                }
                Data.Steps = result.Data;
            }
            catch (Exception ex)
            {
                await MessageService.Error(ex.Message);
            }
        }
    }

    private async void DisCard()
    {
        using (var waitfor = WaitFor.GetWaitFor(this))
        {
            try
            {
                var result = await DataProvider.PostData<AjaxResult>($"/OA_Manage/OA_UserForm/DisCardData", (new { id = Data.Id, remark = Data.Remarks }).ToJson());
                if (!result.Success)
                {
                    throw new Exception(result.Msg);
                }
                OK(new MouseEventArgs());
            }
            catch (Exception ex)
            {
                await MessageService.Error(ex.Message);
            }
        }
    }

    private async void EventData()
    {
        using (var waitfor = WaitFor.GetWaitFor(this))
        {
            try
            {
                var data = new
                {
                    eventName = "MyEvent",
                    eventKey = Data.Id + Data.CurrentStepId,
                    Status = Status,
                    Remarks = Remark
                };
                var result = await DataProvider.PostData<AjaxResult>($"/OA_Manage/OA_UserForm/EventData", data.ToJson());
                if (!result.Success)
                {
                    throw new Exception(result.Msg);
                }
                await MessageService.Success(result.Msg);
                OK(new MouseEventArgs());

            }
            catch (Exception ex)
            {
                await MessageService.Error(ex.Message);
            }
        }
    }

    private async void SaveData()
    {
        using (var waitfor = WaitFor.GetWaitFor(this))
        {
            try
            {
                var result = await DataProvider.PostData<AjaxResult>("/OA_Manage/OA_UserForm/SaveData", Data.ToJson());
                if (!result.Success)
                {
                    throw new Exception(result.Msg);
                }
                await MessageService.Info("操作成功");
                Close();
            }
            catch (Exception ex)
            {
                await MessageService.Error(ex.Message);
            }
        }
    }
}